/*
 * @Author: your name
 * @Date: 2021-08-19 23:34:47
 * @LastEditTime: 2022-01-14 12:28:57
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \node\libs\tools\filetools.ts
 */
const path = require("path")
const fs = require("fs")
import MYSQL from "../sqlcmd/mysql"
//import rds from "../redis/redis"
const config = require("config-lite")(__dirname);
//let cli=new rds(config.redis.host,config.redis.port,config.redis.password);
let mysql = new MYSQL(config.mysql);
//$dirname = "D:\\programs\\canlian\\node\\";
//const $dirname=`/www/wwwroot/rzscl.heiban.fun/`;
const $dirname ="C:\\Users\\lsz588\\Desktop\\caliantupian\\";
export default class filetools {
    constructor() {

    }
    public static uuid(): string {
        const random: (multiplier: number) => number = (multiplier: number) => {
            return Math.floor(Math.random() * multiplier);
        };

        const hexadecimal: (index: number) => string = (index: number) => {
            return ((index === 19) ? random(4) + 8 : random(16)).toString(16);
        };

        const nexttoken: (index: number) => string = (index: number) => {
            if (index === 8 || index === 13 || index === 18 || index === 23) {
                return "-";
            } else if (index === 14) {
                return "4";
            } else {
                return hexadecimal(index);
            }
        };

        const generate: () => string = () => {
            let uuid: string = "";

            while ((uuid.length) < 36) {
                uuid += nexttoken(uuid.length);
            }
            return uuid;
        };

        return generate();
    }
    public static createFilePath = (name) => {
        fs.mkdirSync(name)
    }
    public static createName = (name) => {
        var hz = ".";
        try {
            var array = name.split(".");
            hz += array[array.length - 1];
        } catch (e) {

        };
        return filetools.uuid() + hz;
    }
    public static upLinshiBase64 = async (file_base64, p) => {
        let img = `1.jpg`;
        return new Promise((resolve, reject) => {
            img = filetools.createName(img);
            fs.writeFile(path.resolve('up/rzt/' + img), file_base64, { encoding: 'base64' },  async(err)=> {
                //console.log('File created');
                let obj = { ins_date: new Date(), path: 'up/rzt/'+img, size:file_base64.length, type: 'image/jpeg', name: img, sign: "linshi" };
                let query = await mysql.Insert(obj, "hb_file_record");
                let result = await mysql.Query(query);
                let robj = { fid: result.insertId, ins_date: new Date(), path: 'up/rzt/'+img, size: file_base64.length, type: 'image/jpeg', name: img, sign: "linshi" };
                resolve(robj);
            });
        });

    }
    public static upLinshi = async (file, p) => {
        let size = file.size;
        let name = filetools.createName(file.name);
        return new Promise(async (resolve, reject) => {
            if (!fs.existsSync(path.join($dirname, p))) {
                fs.mkdirSync(path.join($dirname, p));
            };
            let ipath = file.path.replace($dirname + "\\", "");
            ipath = ipath.split("\\");
            ipath = ipath[ipath.length - 1];
            ipath = p + "/" + ipath;
            let obj = { ins_date: new Date(), path: ipath, size: size, type: file.type, name: name, sign: "linshi" };
            let query = await mysql.Insert(obj, "hb_file_record");
            let result = await mysql.Query(query);
            let robj = { fid: result.insertId, ins_date: new Date(), path: ipath, size: size, type: file.type, name: name, sign: "linshi" };
            resolve(robj);
        });
    }
    public static CreateDir = (path) => {
        return new Promise((resolve, reject) => {
            fs.mkdir(path, { recursive: true }, (err) => {
                if (err) reject(err);
                resolve(true);
            });
        });
    }
    public static moveTo = async (oid, newPath, type = null) => {
        return new Promise(async (resolve, reject) => {
            if (!fs.existsSync(path.join($dirname, newPath))) {
                console.log(path.join($dirname, newPath));
                fs.mkdirSync(path.join($dirname, newPath));
            };
            let result = await mysql.Query(`select * from hb_file_record where id=${oid}`);
            console.log(result);
            try {
                result = result[0];
            } catch (e) {
                // console.log(e);
                reject(false);
            };
            fs.rename(path.join($dirname, result.path), path.join($dirname, newPath + "/" + result.name), async (err) => {
                console.log(err);
                let params: any = { path: newPath + "/" + result.name };
                if (type) {
                    params.sign = type;
                };
                var query = await mysql.Update(params, "hb_file_record", { id: oid });
                await mysql.Query(query);
                resolve(params.path);
            });

        });
    }
    public static MoToMany = async (oids, newPath, type = null) => {
        return new Promise(async (resolve, reject) => {
            if (!fs.existsSync(path.join($dirname, newPath))) {
                console.log(path.join($dirname, newPath));
                fs.mkdirSync(path.join($dirname, newPath));
            };
            var query = "select * from hb_file_record where id in (" + oids.concat() + ")";
            var result = await mysql.Query(query);
            var iquery = "";
            var rmsg = [];
            result.forEach(async p => {
                fs.renameSync(path.join($dirname, p.path), path.join($dirname, newPath + "/" + p.name));
                var params: any = { path: newPath + "/" + p.name };
                if (type) {
                    params.sign = type;
                };

                let str111 = await mysql.Update(params, "hb_file_record", { id: p.id }) + ";";
                iquery += str111;
                rmsg.push(config.url + params.path);
            });
            await mysql.Query(iquery);
            resolve(rmsg);
        });
    }
    public static delFile = async (p) => {
        console.log(path.join($dirname, p));
        fs.unlink(path.join($dirname, p), () => {
            //console.log("成了");
        });
        var del = mysql.Delete({ path: p }, "hb_file_record");
        await mysql.Query(del);

    }
}
